﻿using IdentityModel;
using Microsoft.AspNetCore.Mvc;
using Mojito.DI;
using Mojito.Model;

namespace Mojito.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Microsoft.AspNetCore.Authorization.Authorize]
    public class ControllerBase : Microsoft.AspNetCore.Mvc.ControllerBase, IDependency
    {
        /// <summary>
        ///  当前登陆用户
        /// </summary>
        protected UserInfoOutput CurrentUser
        {
            get
            {
                if (User.Identity.IsAuthenticated)
                {
                    var id = User.FindFirst(JwtClaimTypes.Id).Value;
                    return new UserInfoOutput(id);
                }
                return null;
            }
        }

        /// <summary>
        ///  成功消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [NonAction]
        protected IActionResult Success(string message = "操作成功", object data = null)
        {
            var result = new ResponseModel()
            {
                Message = message,
                Code = ResponseModelCode.Success,
                Data = data
            };

            return Ok(result);
        }

        /// <summary>
        ///  失败消息
        /// </summary>
        /// <param name="message"></param>
        /// <param name="code"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [NonAction]
        protected IActionResult Failed(string message = "操作失败", ResponseModelCode code = ResponseModelCode.AppError, object data = null)
        {
            var result = new ResponseModel()
            {
                Message = message,
                Code = code,
                Data = data
            };
            switch (code)
            {
                case ResponseModelCode.UnAuthorize:
                    return Unauthorized(result);
                case ResponseModelCode.ParamError:
                    return Ok(result);
                case ResponseModelCode.AppError:
                    return Ok(result);
                case ResponseModelCode.NotFound:
                    return NotFound(result);
            }
            return StatusCode(500, result);
        }
    }
}
